import React from 'react';
import { Modal, Form, Select, notification } from 'antd';
import { FormComponentProps } from 'antd/es/form';
import { usersList, editUser, EditRoles } from '@/services/api';
import { SIZE, PAGE } from '@/utils/constant';

interface props {
  onClose: () => void;
  dispatch: any;
  roleData: any[];
  searchValue: any;
}

interface UserFormProps extends FormComponentProps {
  ref: any;
  roleData: any[];
  usersData: any[];
}

const enumRoles = {
  teacher: '老师',
  parent: '家长',
  student: '学生',
  guard: '门卫',
};

const ref: any = React.createRef();
const { Item } = Form;
const MyForm = Form.create<UserFormProps>()(
  ({ form: { getFieldDecorator }, usersData, roleData }: any) => {
    const formItemLayout = {
      labelCol: {
        xs: { span: 4, offset: 4 },
      },
      wrapperCol: {
        sm: { span: 8 },
      },
    };
    const roleIds: any = [];
    if (usersData.roles && usersData.roles.length) {
      usersData.roles.forEach((item: any) => {
        roleIds.push(item.pivot.role_id);
      });
    }

    return (
      <Form layout="horizontal" {...formItemLayout}>
        <Item label="角色">
          {getFieldDecorator('role_ids', {
            initialValue: roleIds,
            rules: [
              {
                required: true,
                message: '必填',
              },
            ],
          })(
            <Select placeholder="请选择" allowClear mode="multiple">
              {roleData.map((item: any) => (
                <Select.Option value={item.id} key={item.id}>
                  {enumRoles[item.name]}
                </Select.Option>
              ))}
            </Select>,
          )}
        </Item>
      </Form>
    );
  },
);

const EditRoleModal = ({ roleData, searchValue, onClose, dispatch }: props) => {
  const usersData = JSON.parse(sessionStorage.getItem('usersData') || '');
  return (
    <Modal
      visible
      onCancel={onClose}
      maskClosable={false}
      title="设置角色"
      onOk={() => {
        ref.current.validateFields((err: any, val: any) => {
          if (!err) {
            const newValue: any = {};
            newValue.user_id = usersData.id;
            newValue.role_ids = val.role_ids;

            EditRoles(newValue).then((resp: any) => {
              if (resp.status === 'success') {
                notification.success({ message: '角色设置成功' });
                onClose();
                dispatch({
                  type: 'OPEN_LOADING',
                });
                usersList({ ...searchValue, page: PAGE, size: SIZE })
                  .then((res: any) => {
                    if (res.status === 'success') {
                      dispatch({
                        type: 'GET_DATA',
                        payload: res.data.data,
                      });
                      dispatch({
                        type: 'CHANGE_PAGINATION',
                        payload: {
                          current: PAGE,
                          pageSize: SIZE,
                          total: res.data.meta.total,
                        },
                      });
                    }
                    dispatch({
                      type: 'CLOSED_LOADING',
                    });
                  })
                  .catch(() => {
                    dispatch({
                      type: 'CLOSED_LOADING',
                    });
                  });
              }
            });
          }
        });
      }}
    >
      <MyForm ref={ref} usersData={usersData} roleData={roleData} />
    </Modal>
  );
};

export default EditRoleModal;
